#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import datetime
import time
ETC_DIR = '/etc/djwatchd/'
PLUGINS_DIR = '/etc/djwatchd/plugins/'
STATS_DIR = '/tmp/djwatch/'

import sys; sys.path.insert(0, ETC_DIR)

import settings
from utils import pack

def load_plugins():
    plugins = {}
    func_name = 'get_report'
    for fname in os.listdir(PLUGINS_DIR):
        if not fname.endswith('.py'):
            continue
        name = fname.split('.py')[0]
        if not name.startswith('__'):
            sys.stdout.write('Loading plugin %s... ' % name)
            try:
                mod = __import__('plugins.%s' % name, globals(), locals(), [func_name], -1)
            except ImportError:
                sys.stdout.write('error\n')
            else:
                plugins[name] = getattr(mod, func_name)
                sys.stdout.write('OK\n')
    return plugins

def prepare_stat_dir():
    DUMMY_FILE_NAME = 'dummy'
    if not os.path.exists(STATS_DIR):
        try:
            os.makedirs(STATS_DIR, 0755)
        except os.error:
            print "Failed to create stats directory %s\n" % STATS_DIR
            exit(1)
    dummy_full_path = os.path.join(STATS_DIR, DUMMY_FILE_NAME)
    try:
        f = open(dummy_full_path, 'w')
        f.close()
    except IOError:
        print "No write permissions for stats directory %s\n" % STATS_DIR
        exit(1)
    os.remove(dummy_full_path)

prepare_stat_dir()
plugins = load_plugins()

def get_stat():
    start = time.time()
    try:
        result = dict([k, v()] for k, v in plugins.items())
    except:
        import traceback
        result = {'_error': traceback.format_exc()}
    result['_time'] = time.time() - start
    return result
    
def grab():
    file_full_path = os.path.join(
        STATS_DIR,
        datetime.datetime.now().strftime(settings.STAT_GRAB_FILE_FORMAT)
    )
    f = open(file_full_path, 'w')
    f.write(pack(get_stat()))
    f.close()

def clean_old():
    
    threshold_dt =\
        datetime.datetime.now() - datetime.timedelta(0, settings.STAT_STORE_PERIOD)
    threshold_f = threshold_dt.strftime(settings.STAT_GRAB_FILE_FORMAT)
    
    [os.remove(os.path.join(STATS_DIR, fn))
        for fn in os.listdir(STATS_DIR)
        if fn <= threshold_f]
    
def main():
    period = settings.STAT_GRAB_PERIOD
    while True:
        grab()
        clean_old()
        time.sleep(period)
        
if __name__ == '__main__':
    main()
